<template>
  <div class="c-auth-tree">
    <el-tree
      ref="authTree"
      :key="treeKey"
      :data="roleTreeList"
      :props="defaultProps"
      :default-checked-keys="selectRoleIdList"
      show-checkbox
      node-key="phid"
    />
  </div>
</template>

<script>
import {
  getRoleTreeList, getRoleRuleListById
} from '@/api/role/index'
export default {
  props: {
    // 用户id
    roleId: {
      type: [Number, String],
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      treeKey: 0,
      roleTreeList: [],
      flatRoleListKeys: {}, // 扁平化权限树，并存储节点信息
      selectRoleList: [],
      defaultProps: {
        children: 'children',
        label: 'permName'
      }
    }
  },
  computed: {
    // element-tree 的特性，筛选被勾选的且没有children的节点
    selectRoleIdList() {
      return this.selectRoleList
        .filter(role => this.flatRoleListKeys[role.phid] && !this.flatRoleListKeys[role.phid].hasChildren)
        .map(role => role.phid)
    }
  },
  watch: {
    roleId: 'handleGetRoleRuleInfo'
  },
  created() {
    this.handleGetRoleTreeList().then(() => {
      this.handleGetRoleRuleInfo(this.roleId)
    })
  },
  methods: {
    // 获取所有权限树
    handleGetRoleTreeList() {
      return getRoleTreeList().then(res => {
        if (res.status) {
          this.handleFlatRoleList(res.data)
          this.roleTreeList = res.data
        }
      }).catch(err => {
        console.log(err)
        this.$msgBox.error('获取操作权限失败!')
      })
    },

    // 扁平化treeList 并存储节点信息
    handleFlatRoleList(roleTree) {
      // 递归遍历数组
      const mapTreeArr = list => list.forEach(roleItem => {
        const {
          children,
          phid,
          ...rest
        } = roleItem
        this.disabled && (roleItem.disabled = true)
        this.flatRoleListKeys[phid] = rest
        if (children && children.length) {
          this.flatRoleListKeys[phid].hasChildren = true
          mapTreeArr(children)
        }
      })
      mapTreeArr(roleTree)
    },

    // 通过角色id获取角色权限
    handleGetRoleRuleInfo(roleId, oldRoleId) {
      if (roleId === oldRoleId) return
      getRoleRuleListById({ roleId }).then(({ status, data }) => {
        if (status) {
          this.selectRoleList = data
          this.treeKey = Math.random()
        }
      })
    }
  }
}
</script>
